package cn.rcth.base.serivce.impl;

import cn.rcth.base.constants.BaiseConstants;
import cn.rcth.base.domain.Order;
import cn.rcth.base.domain.OrderProduct;
import cn.rcth.base.domain.Product;
import cn.rcth.base.msg.ResultMsg;
import cn.rcth.base.msg.WechatConfig;
import cn.rcth.base.serivce.IOrderProductSerivce;
import cn.rcth.base.serivce.IOrderSerivce;
import cn.rcth.base.serivce.IPaySerivce;
import cn.rcth.base.serivce.IProductSerivce;
import cn.rcth.base.util.PayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
@Transactional
public class PaySerivceImpl implements IPaySerivce {

    @Autowired
    private IOrderSerivce orderSerivce;

    @Autowired
    private IOrderProductSerivce orderProductSerivce;

    @Override
    public ResultMsg wxPay(Long orderId, String spbill_create_ip, String openId) {
        //根据订单id 查询支付参数
        Order order = orderSerivce.selectOrderById(orderId);
        if (order.getStatus().equals(BaiseConstants.ORDER_CANCELLED)) {
            return ResultMsg.successResult("该订单已经取消,请重新下单");
        }
        //订单商品
        List<OrderProduct> orderProductLists = orderProductSerivce.selestOrderProductByOrderId(orderId);
        //商品描述
        String body = "";
        //商品总价
        BigDecimal zong = new BigDecimal("0");
        for (OrderProduct orderProduct : orderProductLists) {
            Integer count = orderProduct.getCount();
            String productName = orderProduct.getName();
            body = body + "-" + productName;
            BigDecimal totalPrice = orderProduct.getPrice().multiply(new BigDecimal(count));
            zong = zong.add(totalPrice);
        }
        ResultMsg resultMsg = wxPays(body, spbill_create_ip,
                order.getOrderSn(), zong, openId);
        return resultMsg;

    }


    /**
     * 微信支付
     * @param body             商品名称
     * @param spbill_create_ip 用户ip地址
     * @param nexId            订单号
     * @param multiply         总金额
     * @param openId           用户openid
     * @return
     */
    public ResultMsg wxPays(String body, String spbill_create_ip, Long nexId, BigDecimal multiply, String openId) {
        try {
            //金额(微信端按照_分_来进行运算,金额传入之前*100)
            BigDecimal multiply1 = multiply.multiply(new BigDecimal("100"));

            String multiply2 = multiply1 + "";
            String[] split = multiply2.split("\\.");
            //生成的随机字符串
            String nonce_str = getRandomStringByLength(32);
            //商品名称
            //组装参数，用户生成统一下单接口的签名
            Map<String, String> packageParams = new HashMap<>();
            packageParams.put("appid", WechatConfig.appid);//小程序app_id
            packageParams.put("mch_id", WechatConfig.mch_id);//商户号id
            packageParams.put("nonce_str", nonce_str);//随机字符串
            packageParams.put("body", body);//商品名称
            packageParams.put("out_trade_no", nexId + "");//商户订单号,自己的订单ID
            packageParams.put("total_fee", split[0]);//支付金额，这边需要转成字符串类型，否则后面的签名会失败
            packageParams.put("spbill_create_ip", spbill_create_ip);//用户ip地址
            packageParams.put("notify_url", WechatConfig.notify_url);//支付成功后的回调地址
            packageParams.put("trade_type", WechatConfig.TRADETYPE);//支付方式
            packageParams.put("openid", openId + "");//用户的openID，自己获取

            String prestr = PayUtil.createLinkString(packageParams); // 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
            //MD5运算生成签名，这里是第一次签名，用于调用统一下单接口
            String mysign = PayUtil.sign(prestr, WechatConfig.key, "utf-8").toUpperCase();

            //拼接统一下单接口使用的xml数据，要将上一步生成的签名一起拼接进去
            String xml = "<xml>" + "<appid>" + WechatConfig.appid + "</appid>"
                    + "<body><![CDATA[" + body + "]]></body>"
                    + "<mch_id>" + WechatConfig.mch_id + "</mch_id>"
                    + "<nonce_str>" + nonce_str + "</nonce_str>"
                    + "<notify_url>" + WechatConfig.notify_url + "</notify_url>"
                    + "<openid>" + openId + "</openid>"
                    + "<out_trade_no>" + nexId + "</out_trade_no>"
                    + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"
                    + "<total_fee>" + split[0] + "</total_fee>"//支付的金额，单位：分
                    + "<trade_type>" + WechatConfig.TRADETYPE + "</trade_type>"
                    + "<sign>" + mysign + "</sign>"
                    + "</xml>";

            //调用统一下单接口，并接受返回的结果
            String result = PayUtil.httpRequest(WechatConfig.pay_url, "POST", xml);
            // 将解析结果存储在HashMap中
            Map map = PayUtil.doXMLParse(result);

            String return_code = (String) map.get("return_code");//返回状态码
            String result_code = (String) map.get("result_code");//返回状态码

            Map<String, Object> response = new HashMap<String, Object>();//返回给小程序端需要的参数
            if (return_code.equals("SUCCESS") && return_code.equals(result_code)) {
                String prepay_id = (String) map.get("prepay_id");//返回的预付单信息
                response.put("nonceStr", nonce_str);
                response.put("package", "prepay_id=" + prepay_id);
                Long timeStamp = System.currentTimeMillis() / 1000;
                response.put("timeStamp", timeStamp + "");//这边要将返回的时间戳转化成字符串，不然小程序端调用wx.requestPayment方法会报签名错误
                //拼接签名需要的参数
                String stringSignTemp = "appId=" + WechatConfig.appid + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + timeStamp;
                //再次签名，这个签名用于小程序端调用wx.requesetPayment方法
                String paySign = PayUtil.sign(stringSignTemp, WechatConfig.key, "utf-8").toUpperCase();

                response.put("paySign", paySign);
            }

            response.put("appid", WechatConfig.appid);
            System.out.println(response);
            return ResultMsg.successResult(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


        //获取随机字符串
        private String getRandomStringByLength(int length) {
            String base = "abcdefghijklmnopqrstuvwxyz0123456789";
            Random random = new Random();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < length; i++) {
                int number = random.nextInt(base.length());
                sb.append(base.charAt(number));
            }
            return sb.toString();
        }
}
